<template>
  <div class="app-container">
    <span style="font-size: medium;color: rgba(151,170,195) "> / 采购执行 / 订单跟踪</span>

    <el-row style="margin-top: 20px">
      <el-col :span="24" class="card-box">
        <el-card>
          <el-descriptions title="基本信息" size="large">
            <el-descriptions-item label="订单编号:">{{orderInfo.orderNo}}</el-descriptions-item>
            <el-descriptions-item label="收货地址:">{{ orderInfo.deliveryAddress }}</el-descriptions-item>
            <el-descriptions-item label="订单状态:">
              <el-tag size="large">{{orderInfo.orderStatus}}</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="负责人:">{{ orderInfo.responsiblePerson }}</el-descriptions-item>
            <el-descriptions-item label="联系电话:">{{ orderInfo.contactPhone }}</el-descriptions-item>
            <el-descriptions-item label="备注:">{{ orderInfo.remarks }}</el-descriptions-item>
          </el-descriptions>
          <div style="display: flex;justify-content: right" v-if="currentOrderStatusIndex < dictionary['已签收']">
            <el-button type="primary" @click="statusUpdate">
              更新订单状态</el-button>
          </div>
        </el-card>
      </el-col>

      <el-col :span="24" class="card-box">
        <el-card>
          <template #header>
            <Bell style="width: 1em; height: 1em; vertical-align: middle;" />
            <span style="vertical-align: middle; margin-left: 5px">订单状态</span>
          </template>
          <el-row>
            <el-col :span="23">
              <el-steps style="width: 100%"
                        :active="dictionary[orderInfo.orderStatus]"
                        finish-status="success"
                        align-center>
                <el-step class="step" title="待确认" />
                <el-step class="clickable-step" title="已确认">
                  <template #description>
                    <div v-if="currentOrderStatusIndex >= dictionary['已确认']">
                      <el-tag size="default" :type="supplyDetails.length > 0 ? 'primary' : 'info' " style="margin-bottom: 8px;margin-top: 2px"
                              @click="showSupplyDetail">货源详情</el-tag>
                      <el-tag size="default" :type="isQualityInfoUpload('出货质检') ? 'primary' : 'info' "
                              @click="isShowPreShipmentInspection = true;setInspectionFormValue('出货质检')">出货质检</el-tag>
                    </div>
                  </template>
                </el-step>
                <el-step class="clickable-step" title="到出口港">
                  <template #description>
                    <div v-if="currentOrderStatusIndex >= dictionary['到出口港']">
                      <el-tag size="default" :type="isQualityInfoUpload('出港质检') ? 'primary' : 'info' " style="margin-bottom: 8px;margin-top: 2px"
                              @click="isShowPortDepartureInspection = true;setInspectionFormValue('出港质检')">出港质检</el-tag>
                    </div>
                  </template>
                </el-step>
                <el-step class="clickable-step" title="已发货">
                  <template #description>
                    <div v-if="currentOrderStatusIndex >= dictionary['已发货']">
                      <el-tag size="default" :type="purchaseTraceHelp !== undefined ? 'primary' : 'info' " style="margin-bottom: 8px;margin-top: 2px"
                              @click="showLogisticDetail">物流详情</el-tag>
                    </div>
                  </template>
                </el-step>
                <el-step class="clickable-step" title="运送中" >
                  <template #description>
                    <div v-if="currentOrderStatusIndex >= dictionary['运送中']">
                      <el-tag size="default" :type="purchaseTraceHelp !== undefined
                       && purchaseTraceHelp.originLat !== null && purchaseTraceHelp.originLat !== ''? 'primary' : 'info' " style="margin-bottom: 8px;margin-top: 2px"
                              @click="showRealTimeInfo">实时信息</el-tag>
                    </div>
                  </template>
                </el-step>
                <el-step class="clickable-step" title="已送达" >
                  <template #description>
                    <div v-if="currentOrderStatusIndex >= dictionary['已送达']">
                      <el-tag size="default" :type="isQualityInfoUpload('入港质检') ? 'primary' : 'info' " style="margin-bottom: 8px;margin-top: 2px"
                              @click="isShowPortEntryInspection = true;setInspectionFormValue('入港质检')">入港质检</el-tag>
                      <el-tag size="default" :type="purchaseTraceHelp !== undefined
                      && purchaseTraceHelp.receiveManager !== null && purchaseTraceHelp.receiveManager !== '' ? 'primary' : 'info' " style="margin-bottom: 8px;margin-top: 2px"
                              @click="showLogisticDetail">物流更新</el-tag>
                    </div>
                  </template>
                </el-step>
                <el-step class="clickable-step" title="已签收" >
                  <template #description>
                    <div v-if="currentOrderStatusIndex >= dictionary['已签收']">
                      <el-tag size="default" :type="purchaseTraceHelp !== undefined
                      && purchaseTraceHelp.receiveManager !== null && purchaseTraceHelp.receiveManager !== ''
                      && purchaseTraceHelp.receiver !== null && purchaseTraceHelp.receiver !== '' ? 'primary' : 'info' " style="margin-bottom: 8px;margin-top: 2px"
                              @click="showLogisticDetail">物流更新</el-tag>
                    </div>
                  </template>
                </el-step>
                <el-step class="clickable-step" title="调拨规划" >
                  <template #description>
                    <div v-if="currentOrderStatusIndex >= dictionary['调拨规划']">
                      <el-tag size="default" :type="allocationPlans.length > 0 ? 'primary' : 'info' " style="margin-bottom: 8px;margin-top: 2px"
                              @click="isShowAllocationPlan = true">调拨计划</el-tag>
                    </div>
                  </template>
                </el-step>
                <el-step class="step" title="配送中" >
                </el-step>
                <el-step class="step" title="已入库" />
              </el-steps>
            </el-col>
            <el-col :span="1">
              <div style="display: flex;justify-content: right;margin-bottom: 5px">
                <el-tag size="large" type="info">待更新</el-tag>
              </div>
              <div style="display: flex;justify-content: right;">
                <el-tag size="large" type="primary">已更新</el-tag>
              </div>
            </el-col>
          </el-row>
        </el-card>
      </el-col>

      <el-col :span="10" class="card-box">
        <el-card style="height: 537px;">
          <template #header>
            <Message style="width: 1em; height: 1em; vertical-align: middle;" />
            <span style="vertical-align: middle; margin-left: 5px">物流信息</span>
          </template>
          <el-scrollbar max-height="457px">
            <el-timeline style="max-width: 600px;margin-right: 30px">
              <el-timeline-item
                  v-for="(activity, index) in logisticDetails"
                  :key="index"
                  :timestamp="activity.updateTime"
                  :type="index === 0 ? 'primary' : 'info'"
              >
                <div>
                  {{activity.logisticMessage}}
                </div>
              </el-timeline-item>
            </el-timeline>
          </el-scrollbar>
        </el-card>
      </el-col>

      <el-col :span="14" class="card-box">
        <el-card>
          <div id="container" style="position: relative; height: 500px; width: 100%"></div>
        </el-card>
      </el-col>
    </el-row>

    <!--货源详情提交-->
    <el-dialog v-model="isShowSupplyDetail" :show-close="false" width="700px" append-to-body>
      <template #title>
        <span>货源详情 / {{orderNo}}</span>
      </template>
      <el-scrollbar max-height="450px" style="margin-top: -10px">
        <div v-for="(item, index) in supplyDetails" :key="index">
          <el-card style="margin-bottom: 15px">
            <el-form ref="supplyDetailRef" :model="item" :rules="rules" label-width="120px" label-position="top" style="padding-right: 10px">
              <el-row gutter="15">
                <el-col :span="8">
                  <el-form-item label="货品批号" prop="deliveryAddress">
                    <el-input v-model="item.rawProductBatch" placeholder="请输入货品批号" disabled/>
                  </el-form-item>
                  <el-form-item label="生产日期" prop="productionDate">
                    <el-date-picker clearable
                                    v-model="item.productionDate"
                                    value-format="YYYY-MM-DD"
                                    placeholder="请选择生产日期"
                                    :disabled="currentOrderStatusIndex !== dictionary['已确认']">
                    </el-date-picker>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="货品名称" prop="deliveryAddress">
                    <el-input v-model="item.name" placeholder="请输入货品名称" disabled/>
                  </el-form-item>
                  <el-form-item label="保质期" prop="shelfLife">
                    <el-input v-model="item.shelfLife" placeholder="请输入货品件数"
                              :disabled="currentOrderStatusIndex !== dictionary['已确认']">
                      <template #suffix>
                        <span>天</span>
                      </template>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="货源地" prop="origin">
                    <el-input v-model="item.origin" placeholder="请输入货源地"
                              :disabled="currentOrderStatusIndex !== dictionary['已确认']"/>
                  </el-form-item>
                  <el-form-item label="疫苗注射情况" prop="vaccine">
                    <el-select v-model="item.vaccine" placeholder="请选择"
                               :disabled="currentOrderStatusIndex !== dictionary['已确认']">
                      <el-option key="是" label="是" value="是" />
                      <el-option key="否" label="否" value="否" />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row gutter="15">
                <el-col :span="12">
                  <el-form-item label="牧场" prop="ranch">
                    <el-input v-model="item.ranch" placeholder="请输入牧场"
                              :disabled="currentOrderStatusIndex !== dictionary['已确认']"/>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="屠宰场" prop="factory">
                    <el-input v-model="item.factory" placeholder="请输入屠宰场"
                              :disabled="currentOrderStatusIndex !== dictionary['已确认']"/>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-form-item label="饲料" prop="feed">
                <el-input type="textarea" v-model="item.feed" placeholder="请输入饲料"
                          :disabled="currentOrderStatusIndex !== dictionary['已确认']"/>
              </el-form-item>
              <el-form-item label="备注" prop="remarks">
                <el-input type="textarea" v-model="item.remarks" placeholder="请输入备注"
                          :disabled="currentOrderStatusIndex !== dictionary['已确认']"/>
              </el-form-item>
            </el-form>
          </el-card>
        </div>
      </el-scrollbar>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="isShowSupplyDetail = false;initial()">关 闭</el-button>
          <el-button type="primary" @click="submitSupplyDetail" :disabled="currentOrderStatusIndex !== dictionary['已确认']">提 交</el-button>
        </div>
      </template>
    </el-dialog>

    <!--出货质检信息提交-->
    <el-dialog title="出货质检" v-model="isShowPreShipmentInspection" :show-close="false" width="500px" append-to-body>
      <el-form ref="inspectionRef" :model="form" :rules="inspectionRules" label-width="80px" label-position="top">
        <el-row gutter="15">
          <el-col :span="12">
            <el-form-item label="质检机构" prop="inspectionAgency">
              <el-select v-model="form.inspectionAgency" placeholder="请选择检验机构"
                         :disabled="currentOrderStatusIndex !== dictionary['已确认']">
                <el-option v-for="item in inspectionAgency"
                           :key="item.code"
                           :label="formatInspectionAgency(item)"
                           :value="item.name" />
              </el-select>
            </el-form-item>
            <el-form-item label="质检时间" prop="inspectionTime">
              <el-date-picker clearable
                              v-model="form.inspectionTime"
                              value-format="YYYY-MM-DD"
                              placeholder="请选择质检日期"
                              :disabled="currentOrderStatusIndex !== dictionary['已确认']">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="质检人员" prop="inspector">
              <el-input v-model="form.inspector" placeholder="请输入检验人员"
                        :disabled="currentOrderStatusIndex !== dictionary['已确认']"/>
            </el-form-item>
            <el-form-item label="质检结果" prop="inspectionResult">
              <el-select v-model="form.inspectionResult" placeholder="请选择质检结果"
                         :disabled="currentOrderStatusIndex !== dictionary['已确认']">
                <el-option label="合格" value="合格"></el-option>
                <el-option label="不合格" value="不合格"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="报告附件" prop="reportAttachment">
          <file-upload v-model="form.reportAttachment"
                       limit="5"
                       :disabled="currentOrderStatusIndex !== dictionary['已确认']"/>
        </el-form-item>
        <el-form-item label="质检备注" prop="remarks">
          <el-input type="textarea" v-model="form.remarks" placeholder="请输入备注"
                    :disabled="currentOrderStatusIndex !== dictionary['已确认']"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="isShowPreShipmentInspection = false;initial()">关 闭</el-button>
        <el-button type="primary" @click="submitPreShipmentInspectionInfo()" :disabled="currentOrderStatusIndex !== dictionary['已确认']">提 交</el-button>
      </template>
    </el-dialog>

    <!--出港质检信息提交-->
    <el-dialog title="出港质检" v-model="isShowPortDepartureInspection" :show-close="false" width="500px" append-to-body>
      <el-form ref="portDepartureInspectionRef" :model="form" :rules="inspectionRules" label-width="80px" label-position="top">
        <el-row gutter="15">
          <el-col :span="12">
            <el-form-item label="质检机构" prop="inspectionAgency">
              <el-select v-model="form.inspectionAgency" placeholder="请选择检验机构"
                         :disabled="currentOrderStatusIndex !== dictionary['到出口港']">
                <el-option v-for="item in inspectionAgency"
                           :key="item.code"
                           :label="formatInspectionAgency(item)"
                           :value="item.name" />
              </el-select>
            </el-form-item>
            <el-form-item label="质检时间" prop="inspectionTime">
              <el-date-picker clearable
                              v-model="form.inspectionTime"
                              value-format="YYYY-MM-DD"
                              placeholder="请选择质检日期"
                              :disabled="currentOrderStatusIndex !== dictionary['到出口港']">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="质检人员" prop="inspector">
              <el-input v-model="form.inspector" placeholder="请输入检验人员"
                        :disabled="currentOrderStatusIndex !== dictionary['到出口港']"/>
            </el-form-item>
            <el-form-item label="质检结果" prop="inspectionResult">
              <el-select v-model="form.inspectionResult" placeholder="请选择质检结果"
                         :disabled="currentOrderStatusIndex !== dictionary['到出口港']">
                <el-option label="合格" value="合格"></el-option>
                <el-option label="不合格" value="不合格"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="报告附件" prop="reportAttachment">
          <file-upload v-model="form.reportAttachment"
                       limit="5"
                       :disabled="currentOrderStatusIndex !== dictionary['到出口港']"/>
        </el-form-item>
        <el-form-item label="质检备注" prop="remarks">
          <el-input type="textarea" v-model="form.remarks" placeholder="请输入备注"
                    :disabled="currentOrderStatusIndex !== dictionary['到出口港']"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="isShowPortDepartureInspection = false;initial()">关 闭</el-button>
        <el-button type="primary" @click="submitPortDepartureInspectionInfo()" :disabled="currentOrderStatusIndex !== dictionary['到出口港']">提 交</el-button>
      </template>
    </el-dialog>

    <!--入港质检信息提交-->
    <el-dialog title="入港质检" v-model="isShowPortEntryInspection" :show-close="false" width="500px" append-to-body>
      <el-form ref="portEntryInspectionRef" :model="form" :rules="inspectionRules" label-width="80px" label-position="top">
        <el-row gutter="15">
          <el-col :span="12">
            <el-form-item label="质检机构" prop="inspectionAgency">
              <el-select v-model="form.inspectionAgency" placeholder="请选择检验机构"
                         :disabled="currentOrderStatusIndex !== dictionary['已送达']">
                <el-option v-for="item in inspectionAgency"
                           :key="item.code"
                           :label="formatInspectionAgency(item)"
                           :value="item.name" />
              </el-select>
            </el-form-item>
            <el-form-item label="质检时间" prop="inspectionTime">
              <el-date-picker clearable
                              v-model="form.inspectionTime"
                              value-format="YYYY-MM-DD"
                              placeholder="请选择质检日期"
                              :disabled="currentOrderStatusIndex !== dictionary['已送达']">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="质检人员" prop="inspector">
              <el-input v-model="form.inspector" placeholder="请输入检验人员"
                        :disabled="currentOrderStatusIndex !== dictionary['已送达']"/>
            </el-form-item>
            <el-form-item label="质检结果" prop="inspectionResult">
              <el-select v-model="form.inspectionResult" placeholder="请选择质检结果"
                         :disabled="currentOrderStatusIndex !== dictionary['已送达']">
                <el-option label="合格" value="合格"></el-option>
                <el-option label="不合格" value="不合格"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="报告附件" prop="reportAttachment">
          <file-upload v-model="form.reportAttachment"
                       limit="5"
                       :disabled="currentOrderStatusIndex !== dictionary['已送达']"/>
        </el-form-item>
        <el-form-item label="质检备注" prop="remarks">
          <el-input type="textarea" v-model="form.remarks" placeholder="请输入备注"
                    :disabled="currentOrderStatusIndex !== dictionary['已送达']"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="isShowPortEntryInspection = false;initial()">关 闭</el-button>
        <el-button type="primary" @click="submitPortEntryInspectionInfo()" :disabled="currentOrderStatusIndex !== dictionary['已送达']">提 交</el-button>
      </template>
    </el-dialog>

    <!--物流信息展示-->
    <el-dialog title="物流信息" v-model="isShowPurchaseTrace" :show-close="false" width="700px" append-to-body>
      <el-scrollbar max-height="450px">
        <el-form ref="shipRef" :model="purchaseTrace" label-width="110px" label-position="top" style="padding-right: 10px" :rules="traceRules">
          <el-row gutter="15">
            <el-col :span="8">
              <el-form-item label="订单编号" prop="orderNo">
                <el-input v-model="purchaseTrace.orderNo" placeholder="请输入订单编号" disabled/>
              </el-form-item>
              <el-form-item label="物流商名称" prop="logisticName">
                <el-input v-model="purchaseTrace.logisticName" placeholder="请输入物流商名称"
                          :disabled="currentOrderStatusIndex !== dictionary['已发货']"/>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="物流编号" prop="logisticNo">
                <el-input v-model="purchaseTrace.logisticNo" placeholder="请输入物流编号"
                          :disabled="currentOrderStatusIndex !== dictionary['已发货']"/>
              </el-form-item>
              <el-form-item label="联系电话" prop="contactPhone">
                <el-input v-model="purchaseTrace.contactPhone" placeholder="请输入联系电话"
                          :disabled="currentOrderStatusIndex !== dictionary['已发货']"/>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="出港时间" prop="departureTime">
                <el-date-picker clearable
                                v-model="purchaseTrace.departureTime"
                                type="datetime"
                                format="YYYY-MM-DD HH:mm:ss"
                                value-format="YYYY-MM-DD HH:mm:ss"
                                placeholder="请选择出港时间"
                                :disabled="currentOrderStatusIndex !== dictionary['已发货']">
                </el-date-picker>
              </el-form-item>
              <el-form-item label="预计到货时间" prop="expectedDeliveryTime">
                <el-date-picker clearable
                                v-model="purchaseTrace.expectedDeliveryTime"
                                value-format="YYYY-MM-DD"
                                placeholder="请选择预计到货时间"
                                :disabled="currentOrderStatusIndex !== dictionary['已发货']">
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row gutter="15">
            <el-col :span="24">
              <el-form-item label="备注" prop="departureRemarks">
                <el-input type="textarea" v-model="purchaseTrace.departureRemarks" placeholder="请输入备注"
                          :disabled="currentOrderStatusIndex !== dictionary['已发货']"/>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div v-show="currentOrderStatusIndex >= dictionary['已送达']">
          <el-divider content-position="center">到货信息</el-divider>
          <el-form ref="arriveRef" :model="purchaseTrace" label-width="110px" label-position="top" v-show="currentOrderStatusIndex >= dictionary['已送达']" :rules="traceRules" style="padding-right: 10px">
            <el-row gutter="15">
              <el-col :span="8">
                <el-form-item label="收货负责人" prop="receiveManager">
                  <el-input v-model="purchaseTrace.receiveManager" placeholder="请输入收货负责人"
                            :disabled="currentOrderStatusIndex !== dictionary['已送达']"/>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="联系电话" prop="receiveContact">
                  <el-input v-model="purchaseTrace.receiveContact" placeholder="请输入联系电话"
                            :disabled="currentOrderStatusIndex !== dictionary['已送达']"/>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="实际到货时间" prop="actualDeliveryTime">
                  <el-date-picker clearable
                                v-model="purchaseTrace.actualDeliveryTime"
                                type="datetime"
                                format="YYYY-MM-DD HH:mm:ss"
                                value-format="YYYY-MM-DD HH:mm:ss"
                                placeholder="请选择实际到货时间"
                                :disabled="currentOrderStatusIndex !== dictionary['已送达']">
                  </el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row gutter="15">
              <el-col :span="24">
                <el-form-item label="备注" prop="receiveRemarks">
                  <el-input type="textarea" v-model="purchaseTrace.receiveRemarks" placeholder="请输入备注"
                            :disabled="currentOrderStatusIndex !== dictionary['已送达']"/>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
        <div v-show="currentOrderStatusIndex >= dictionary['已签收']">
          <el-divider content-position="center">收货信息</el-divider>
          <el-form ref="receiveRef" :model="purchaseTrace" label-width="110px" label-position="top" v-show="currentOrderStatusIndex >= dictionary['已签收']" :rules="traceRules" style="padding-right: 10px">
            <el-row gutter="15">
              <el-col :span="8">
                <el-form-item label="收货人" prop="receiver">
                  <el-input v-model="purchaseTrace.receiver" placeholder="请输入收货人"
                            :disabled="currentOrderStatusIndex !== dictionary['已签收']"/>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="收货时间:" prop="receiveTime">
                  <el-date-picker clearable
                                v-model="purchaseTrace.receiveTime"
                                type="datetime"
                                format="YYYY-MM-DD HH:mm:ss"
                                value-format="YYYY-MM-DD HH:mm:ss"
                                placeholder="请选择收货时间"
                                :disabled="currentOrderStatusIndex !== dictionary['已签收']">
                  </el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </el-scrollbar>
      <template #footer>
        <el-button @click="isShowPurchaseTrace = false;initial()">关 闭</el-button>
        <el-button @click="submitPurchaseTrace" type="primary" :disabled="currentOrderStatusIndex >= dictionary['调拨规划']">提交</el-button>
      </template>
    </el-dialog>

    <!--调拨规划展示-->
    <el-dialog title="调拨规划" v-model="isShowAllocationPlan" :show-close="false" width="900px" append-to-body>
      <el-scrollbar max-height="450px">
        <el-empty description="还未设置调拨计划" v-show="allocationPlans.length === 0"/>
        <el-table :data="allocationPlans" v-show="allocationPlans.length > 0">
          <el-table-column label="调拨编号" align="center" prop="allocationNo"/>
          <el-table-column label="物流商编码" align="center" prop="deliveryCode"/>
          <el-table-column label="物流商" align="center" prop="deliveryName"/>
          <el-table-column label="仓库编号" align="center" prop="warehouseNo"/>
          <el-table-column label="发货地" align="center" prop="shippingPlace"/>
          <el-table-column label="调拨时间" align="center" prop="allocationDate">
            <template #default="scope">
              {{ parseTime(scope.row.allocationDate, '{y}-{m}-{d}') }}
            </template>
          </el-table-column>
          <el-table-column label="备注" fixed="right" align="center" prop="remarks"/>
        </el-table>
      </el-scrollbar>
      <template #footer>
        <el-button @click="isShowAllocationPlan = false" type="primary">关 闭</el-button>
      </template>
    </el-dialog>

    <!--实时信息更新（当前位置经纬度，预计到达时间）-->
    <el-dialog
        title="实时信息更新"
        v-model="isShowRealTimeInfo"
        width="50%"
        style="border-radius: 12px;
        display: flex;
        flex-direction: column;
        margin: 0 !important;
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        max-height: calc(100% - 30px);
        max-width: calc(100% - 30px);
        justify-content: center;"
        :close-on-click-modal="false"
        :show-close="false">
      <el-form ref="realTimeInfoRef" :model="purchaseTrace" label-width="110px" label-position="top" :rules="realTimeRules" style="padding-right: 10px">
        <el-row gutter="15">
          <el-col :span="12">
            <el-form-item label="出发点经度" prop="originLng">
              <el-input v-model="purchaseTrace.originLng" placeholder="请输入经度" prefix-icon="Location"
                        :disabled="currentOrderStatusIndex !== dictionary['运送中']">
                <template #suffix>
                  <span>°</span>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item label="当前位置经度" prop="currentLng">
              <el-input v-model="purchaseTrace.currentLng" placeholder="请输入经度" prefix-icon="Location"
                        :disabled="currentOrderStatusIndex !== dictionary['运送中']">
                <template #suffix>
                  <span>°</span>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item label="预计到货时间" prop="expectedDeliveryTime">
              <el-date-picker clearable
                              v-model="purchaseTrace.expectedDeliveryTime"
                              value-format="YYYY-MM-DD"
                              placeholder="请选择预计到货时间"
                              style="width: 100%"
                              :disabled="currentOrderStatusIndex !== dictionary['运送中']">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出发点纬度" prop="originLat">
              <el-input v-model="purchaseTrace.originLat" placeholder="请输入纬度" prefix-icon="Location"
                        :disabled="currentOrderStatusIndex !== dictionary['运送中']">
                <template #suffix>
                  <span>°</span>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item label="当前位置纬度" prop="currentLat">
              <el-input v-model="purchaseTrace.currentLat" placeholder="请输入经度" prefix-icon="Location"
                        :disabled="currentOrderStatusIndex !== dictionary['运送中']">
                <template #suffix>
                  <span>°</span>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="isShowRealTimeInfo = false;initial()">关 闭</el-button>
          <el-button type="primary" @click="submitRealTimeInfo" :disabled="currentOrderStatusIndex !== dictionary['运送中']">提 交</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="LogisticDetail">

import {getPurchaseOrder, updatePurchaseOrderStatus} from "@/api/purchase/purchaseOrder.js";
import {parseTime} from "@/utils/ruoyi.js";
import {Message} from "@element-plus/icons-vue";
import AMapLoader from "@amap/amap-jsapi-loader"
import {onMounted,onUnmounted} from "vue"
import {getOrderDetail} from "@/api/purchase/orderDetail.js";
import {getSupplyDetailByBatches, updateSupplyDetail, updateSupplyDetailList} from "@/api/purchase/supplyDetail.js";
import {listQualityInfoByOrderNo, updateQualityInfo} from "@/api/purchase/qualityInfo.js";
import {getPurchaseTrace, updatePurchaseTrace} from "@/api/purchase/PurchaseTrace.js";
import {getLogisticDetailByOrderNo} from "@/api/purchase/LogisticDetail.js";
import {ElStep, ElSteps} from "element-plus";
import {getAllocationPlanByOrderNo} from "@/api/purchase/AllocationPlan.js";
import shipImage from "@/assets/icons/png/货轮.png";
import startImage from "@/assets/icons/png/起点.png"
import endImage from "@/assets/icons/png/终点.png"
import {listDictDataAll} from "@/api/purchase/DictData.js";

const {proxy} = getCurrentInstance();

let map = null;

const orderNo = ref('');
const orderInfo = ref({});
const orderDetails = ref([]);
const supplyDetails = ref([]);
const inspectionInfos = ref([]);
const purchaseTrace = ref({});
const logisticDetails = ref([]);
const allocationPlans = ref([]);
const dictionary = {
  '待确认': 1,
  '已确认': 2,
  '到出口港': 3,
  '已发货': 4,
  '运送中': 5,
  '已送达': 6,
  '已签收': 7,
  '调拨规划': 8,
  '配送中': 9,
  '已入库': 10
}
const rules = {
  origin:[
    { required: true, message: "货源地不能为空", trigger: "blur" }
  ],
  productionDate:[
    { required: true, message: "生产日期不能为空", trigger: "blur" }
  ],
  shelfLife:[
    { required: true, message: "保质期不能为空", trigger: "blur" }
  ],
  ranch:[
    { required: true, message: "牧场不能为空", trigger: "blur" }
  ],
  factory:[
    { required: true, message: "屠宰场不能为空", trigger: "blur" }
  ],
  vaccine:[
    { required: true, message: "疫苗注射情况不能为空", trigger: "blur" }
  ],
}
const inspectionRules = {
  inspectionAgency:[
    { required: true, message: "质检人机构不能为空", trigger: "blur" }
  ],
  inspector:[
    { required: true, message: "质检人姓名不能为空", trigger: "blur" }
  ],
  inspectionTime:[
    { required: true, message: "质检日期不能为空", trigger: "blur" }
  ],
  inspectionResult:[
    { required: true, message: "质检结果不能为空", trigger: "blur" }
  ],
}
const traceRules = {
  logisticName:[
    { required: true, message: "物流商名称不能为空", trigger: "blur" }
  ],
  logisticNo:[
    { required: true, message: "物流编号不能为空", trigger: "blur" }
  ],
  contactPhone:[
    { required: true, message: "联系电话不能为空", trigger: "blur" }
  ],
  departureTime:[
    { required: true, message: "离港时间不能为空", trigger: "blur" }
  ],
  expectedDeliveryTime:[
    { required: true, message: "预计到货时间不能为空", trigger: "blur" }
  ],
  receiveManager:[
    { required: true, message: "收货负责人姓名不能为空", trigger: "blur" }
  ],
  receiveContact:[
    { required: true, message: "收货负责人手机号不能为空", trigger: "blur" }
  ],
  actualDeliveryTime:[
    { required: true, message: "实际到港时间不能为空", trigger: "blur" }
  ],
  receiver:[
    { required: true, message: "收货人不能为空", trigger: "blur" }
  ],
  receiveTime:[
    { required: true, message: "收货时间不能为空", trigger: "blur" }
  ]
}
const realTimeRules = {
  originLng:[
    { required: true, message: "起始地经度不能为空", trigger: "blur" }
  ],
  originLat:[
    { required: true, message: "起始地纬度不能为空", trigger: "blur" }
  ],
  expectedDeliveryTime:[
    { required: true, message: "预计到达时间不能为空", trigger: "blur" }
  ]
}
const purchaseTraceHelp = ref({});

const isShowSupplyDetail = ref(false); // 货源详情展示
const isShowPreShipmentInspection = ref(false); // 出货质检
const isShowPortDepartureInspection = ref(false); // 出港质检
const isShowPortEntryInspection = ref(false); //入港质检
const isShowPurchaseTrace = ref(false); // 订单跟踪信息展示
const isShowAllocationPlan = ref(false);
const isShowRealTimeInfo = ref(false);

const currentOrderStatusIndex = ref(1);
const form = ref({}); //质检信息

const inspectionAgency = ref([]); //质检机构

onMounted(() => {
  window._AMapSecurityConfig = {
    securityJsCode: "4cb512290cb2f2cde33ae3284c6b8073",
  };
  AMapLoader.load({
    key: "48dff654e078158ff016c701f2755ddf",
    version: "2.0",
    plugins: ["AMap.Scale","AMap.Driving","AMap.Geocoder"],
  })
      .then((AMap) => {
        map = new AMap.Map("container", {
          viewMode: "3D", // 是否为3D地图模式
          zoom: 4, // 初始化地图级别
          center: [116.397428, 39.90923],
        });

        const startIcon = new AMap.Icon({
          image: startImage,
          size: new AMap.Size(38, 38),
          imageSize: new AMap.Size(38, 38)
        });

        const endIcon = new AMap.Icon({
          image: endImage,
          size: new AMap.Size(35, 35),
          imageSize: new AMap.Size(35, 35)
        });

        const boatIcon = new AMap.Icon({
          image: shipImage,
          size: new AMap.Size(28, 30),
          imageSize: new AMap.Size(28, 30)
        });

        //终点标记
        setTimeout(() => {
          let endPoint =[];
          if(orderInfo.value.destinationLng !== null && orderInfo.value.destinationLat !== null
              && orderInfo.value.destinationLng !== 0.0 && orderInfo.value.destinationLat !== 0.0){
            endPoint = [orderInfo.value.destinationLng, orderInfo.value.destinationLat];
            const endMaker =  new AMap.Marker({
              position: endPoint,
              icon: endIcon,
              offset: new AMap.Pixel(-10, -28),
            });
            map.add(endMaker);
            map.setCenter(endPoint);
          }
        },500);

        //起点标记
        setTimeout(() => {
          if(purchaseTraceHelp.value !== undefined
              && purchaseTraceHelp.value.originLat !== null){
            const startMaker =  new AMap.Marker({
              position: [purchaseTraceHelp.value.originLng, purchaseTraceHelp.value.originLat],
              icon: startIcon,
              offset: new AMap.Pixel(-10, -28),
            });
            map.add(startMaker);
            map.setCenter([purchaseTraceHelp.value.originLng, purchaseTraceHelp.value.originLat]);
          }
        }, 1000);

        //货船标记
        setTimeout(() => {
          if(purchaseTraceHelp.value !== undefined
              && purchaseTraceHelp.value.currentLat !== null){
            const boatMaker =  new AMap.Marker({
              position: [purchaseTraceHelp.value.currentLng, purchaseTraceHelp.value.currentLat],
              icon: boatIcon,
              offset: new AMap.Pixel(-10, -28),
            });
            boatMaker.on('click',()=>{
              openBoatInfo();
            })
            map.add(boatMaker);
            map.setCenter([purchaseTraceHelp.value.currentLng, purchaseTraceHelp.value.currentLat]);
            openBoatInfo();
          }
        }, 1500);
      })
      .catch((e) => {
        console.log(e);
      });
})

onUnmounted(() => {
  map?.destroy();
})

function openBoatInfo(){
  const content = computed(() => [
    `<div style="font-size: small"><b>${orderInfo.value.orderStatus}</b>`,
    `当前位置:经(${purchaseTraceHelp.value.currentLng})/ 纬(${purchaseTraceHelp.value.currentLat})`,
    `预计到达时间:${purchaseTraceHelp.value.expectedDeliveryTime}</div>`
  ]);
  const infoWindow = new AMap.InfoWindow({
    content: content.value.join('<br>'),
    anchor: 'top-left',
  });
  infoWindow.open(map, [purchaseTraceHelp.value.currentLng, purchaseTraceHelp.value.currentLat]);
}

function initial(){
  if(proxy.$route.query.orderNo){
    orderNo.value = proxy.$route.query.orderNo;
    getPurchaseOrder(orderNo.value).then(response => {
      orderInfo.value = response.data;
      currentOrderStatusIndex.value = dictionary[orderInfo.value.orderStatus];
    })
    getOrderDetail(orderNo.value).then(response => {
      orderDetails.value = response.data;
      if(orderDetails.value.length > 0){
        let rawProductBatches = orderDetails.value.map(item => item.rawProductBatch);
        getSupplyDetailByBatches(rawProductBatches).then(response => {
          supplyDetails.value = response.data;
        })
      }
    })
    listQualityInfoByOrderNo(orderNo.value).then(response => {
      inspectionInfos.value = response.data;
    })
    getPurchaseTrace(orderNo.value).then(response => {
      purchaseTraceHelp.value = response.data;
    })
    getAllocationPlanByOrderNo(orderNo.value).then(response => {
      allocationPlans.value = response.data;
    })
    getLogisticDetailByOrderNo(orderNo.value).then(response => {
      logisticDetails.value = response.data;
    })
    const query = {type: '质检机构'}
    listDictDataAll(query).then(response => {
      inspectionAgency.value = response.data;
    })
  }
}

/** 截取url获取文件名*/
function getFilename(url) {
  return url.substring(url.lastIndexOf('/') + 1);
}

/** 状态更新 */
function statusUpdate(){
  let currentStatus = convert(currentOrderStatusIndex.value);
  let nextStatus = convert(currentOrderStatusIndex.value + 1);
  if(currentStatus === '已确认'){
    if(supplyDetails.value.length === 0 || !isQualityInfoUpload("出货质检")){
      proxy.$modal.msgWarning('请先完善当前状态信息！')
      return;
    }
  }
  if(currentStatus === '到出口港'){
    if(!isQualityInfoUpload("出港质检")){
      proxy.$modal.msgWarning('请先完善当前状态信息！')
      return;
    }
  }
  if(currentStatus === '已发货'){
    if(purchaseTraceHelp.value === undefined){
      proxy.$modal.msgWarning('请先完善当前状态信息！')
      return;
    }
  }
  if(currentStatus === '运送中'){
    if(purchaseTraceHelp.value.originLat === null){
      proxy.$modal.msgWarning('请先完善当前状态信息！')
      return;
    }
  }
  if(currentStatus === '已送达'){
    if(!isQualityInfoUpload("入港质检") || purchaseTraceHelp.value.receiveManager === null){
      proxy.$modal.msgWarning('请先完善当前状态信息！')
      return;
    }
  }
  proxy.$modal.confirm('是否确认将订单状态由\'' + currentStatus + '\'更新为\''
      + nextStatus + '\'，修改后\'' + currentStatus + '\'状态下的信息将无法修改？')
      .then(function() {
        orderInfo.value.orderStatus = nextStatus;
        updatePurchaseOrderStatus(orderInfo.value).then(response => {
          proxy.$modal.msgSuccess("状态更新成功");
          initial();
        })
      })
}

/** 将状态编号转化为状态名称 */
function convert(index){
  for (let dictionaryKey in dictionary) {
    if(dictionary[dictionaryKey] === index){
      return dictionaryKey;
    }
  }
}

/** 输入质检类型返回是否存在 */
function isQualityInfoUpload(type){
  for(let i = 0; i < inspectionInfos.value.length; i++){
    if(inspectionInfos.value[i].inspectionType === type){
      return true;
    }
  }
  return false;
}

function showSupplyDetail(){
  isShowSupplyDetail.value = true;
  if(supplyDetails.value.length === 0){
    supplyDetails.value = orderDetails.value;
    supplyDetails.value.forEach(item => {
      item.name = item.rawProductName;
      item.supplierCode = orderInfo.value.companyName;
    })
  }
}

/** 更新货源详情 **/
function submitSupplyDetail(){
  updateSupplyDetailList(supplyDetails.value).then(response => {
    proxy.$modal.msgSuccess("更新成功");
    isShowSupplyDetail.value = false;
  })
}

/** 为form赋值 */
function setInspectionFormValue(type){
  form.value = {};
  inspectionInfos.value.forEach(item => {
    if(item.inspectionType === type){
      form.value = item;
    }
  })
  form.value.inspectionType = type;
}

/** 提交出货质检信息 */
function submitPreShipmentInspectionInfo(){
  proxy.$refs["inspectionRef"].validate(valid => {
    if (valid) {
      if(form.value.inspectionNo === undefined){
        form.value.inspectionNo = generateInspectionNo();
      }
      if(form.value.orderNo === undefined){
        form.value.orderNo = orderInfo.value.orderNo;
      }
      updateQualityInfo(form.value).then(response => {
        proxy.$modal.msgSuccess("更新成功");
        isShowPreShipmentInspection.value = false;
        initial();
      })
    }
  })
}

/** 提交出港质检信息 */
function submitPortDepartureInspectionInfo(){
  proxy.$refs["portDepartureInspectionRef"].validate(valid => {
    if (valid) {
      if(form.value.inspectionNo === undefined){
        form.value.inspectionNo = generateInspectionNo();
      }
      if(form.value.orderNo === undefined){
        form.value.orderNo = orderInfo.value.orderNo;
      }
      updateQualityInfo(form.value).then(response => {
        proxy.$modal.msgSuccess("更新成功");
        isShowPortDepartureInspection.value = false;
        initial();
      })
    }
  })
}

/** 提交入港质检信息 */
function submitPortEntryInspectionInfo(){
  proxy.$refs["portEntryInspectionRef"].validate(valid => {
    if (valid) {
      if(form.value.inspectionNo === undefined){
        form.value.inspectionNo = generateInspectionNo();
      }
      if(form.value.orderNo === undefined){
        form.value.orderNo = orderInfo.value.orderNo;
      }
      updateQualityInfo(form.value).then(response => {
        proxy.$modal.msgSuccess("更新成功");
        isShowPortEntryInspection.value = false;
        initial();
      })
    }
  })
}

/** 展示物流详情并初始化 */
function showLogisticDetail(){
  console.log(purchaseTraceHelp.value);
  if(purchaseTraceHelp.value === undefined){
    purchaseTrace.value = {};
    purchaseTrace.value.orderNo = orderNo.value;
  }
  else{
    purchaseTrace.value = purchaseTraceHelp.value;
  }
  isShowPurchaseTrace.value = true;
}

/** 提交物流跟踪信息 **/
function submitPurchaseTrace(){
  if(currentOrderStatusIndex.value === dictionary['已发货']){
    proxy.$refs["shipRef"].validate(valid => {
      if (valid) {
        updatePurchaseTrace(purchaseTrace.value).then(response => {
          proxy.$modal.msgSuccess("更新成功");
          isShowPurchaseTrace.value = false;
          initial();
        })
      }
    })
  }
  else if(currentOrderStatusIndex.value === dictionary['已送达']){
    proxy.$refs["arriveRef"].validate(valid => {
      if (valid) {
        updatePurchaseTrace(purchaseTrace.value).then(response => {
          proxy.$modal.msgSuccess("更新成功");
          isShowPurchaseTrace.value = false;
          initial();
        })
      }
    })
  }
  else if(currentOrderStatusIndex.value === dictionary['已签收']){
    proxy.$refs["receiveRef"].validate(valid => {
      if (valid) {
        updatePurchaseTrace(purchaseTrace.value).then(response => {
          proxy.$modal.msgSuccess("更新成功");
          isShowPurchaseTrace.value = false;
          initial();
        })
      }
    })
  }
}

/** 展示实时信息 */
function showRealTimeInfo(){
  if(purchaseTraceHelp.value === undefined){
    purchaseTrace.value = {};
    purchaseTrace.value.orderNo = orderNo.value;
  }
  else{
    purchaseTrace.value = purchaseTraceHelp.value;
  }
  isShowRealTimeInfo.value = true;
}

/** 提交实时信息 */
function submitRealTimeInfo(){
  proxy.$refs["realTimeInfoRef"].validate(valid => {
    if (valid) {
      updatePurchaseTrace(purchaseTrace.value).then(response => {
        proxy.$modal.msgSuccess("更新成功");
        isShowRealTimeInfo.value = false;
        initial();
      })
    }
  })
}

/** 随机生成质检编号 */
function generateInspectionNo() {
  // 定义字符集，可以根据需要调整
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
  let batchNumber = '';
  for (let i = 0; i < 3; i++) {
    const randomIndex = Math.floor(Math.random() * chars.length);
    batchNumber += chars[randomIndex];
  }
  return 'INSPECT' + batchNumber;
}

/** 格式化质检信息 **/
function formatInspectionAgency(item){
  return item.code + " - " + item.name;
}

initial()
</script>

<style scoped lang="scss">
#container{
  width: 100%;
  height: 100%;
}
.demo-tabs > .el-tabs__content {
  padding: 32px;
  color: #6b778c;
  font-size: 32px;
  font-weight: 600;
}
.clickable-step {
  cursor: pointer;
}
.sub-row {
  padding: 12px;
  border-bottom: 1px solid #ebeef5;

  &:last-child {
    border-bottom: none;
  }
}
.desc-box {
  :deep(.el-descriptions__header) {
    display: none; /* 隐藏标题 */
  }

  :deep(.el-descriptions__body) {
    background: transparent;
  }
}
.two-column {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  height: 90%;
  margin-top: 30px;
}
</style>